import Common from '../../../common/common.js';
let common = new Common;
var PAGINATE = require('../../../common/paginate.js')
Page({
  data: {
    parm: {},//参数
    //当前tab页序号
    currentTab: 0,
    //标签页是否已加载过
    tabLoadedArray: Array(10).fill(false),
    //对账总体情况
    summaryArray: Array(10).fill({}),
    //对账列表
    reconciliationListArray: Array(10).fill([]),
    //是否显示底部按钮和复选框
    manageOpe: false,
    //是否显示底部按钮和复选框
    manageOpeOrder: false,
    //是否全选
    checkedAll: false,
    //必传，清分状态：1待清分 2已清分 3已到账
    status: "2",
    //可选，查询订单月份
    month: "",
    orderIdList: [],//选择订单id列表
    feeMoney: [],//选择的手续费
    allPrice: [],//选择的开票金额
    sorting: [],//清分数组
    pageNumber: 1,
  },
  // 跳转问题详情
  detile: function () {
    wx.navigateTo({
      url: '/pages/myCenter/problemDetil/problemDetil?code=' + 4 + '&type=' + 1,
    })
  },
  // 复制交易流水号
  copy: function (e) {
    let text = e.currentTarget.dataset.num.toString();
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.showToast({
          title: '交易流水号复制成功！',
          icon: 'none'
        })
        wx.getClipboardData({
          success: function (res) { }
        })
      }
    })
  },
  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  /**
   * 切换全部商品/未上架商品/已上架商品tab页
   */
  switchTab: function (e) {
    var currentTab = 0;
    if (typeof (e) === 'string' || typeof (e) === 'number') {
      currentTab = e;
    } else {
      currentTab = e.currentTarget.dataset.current;
    }
    //设置参数
    this.setData({
      currentTab: currentTab,
      //是否显示底部按钮和复选框
      manageOpe: false,
      //是否显示底部按钮和复选框
      manageOpeOrder: false,
      pageNumber: 1,
      clickQingFen: 1, //防止死循环
    })
    this.goTop()//回到顶部 
    this.getSummary();
    this.getList(1, 1);
    this.data.reconciliationListArray[currentTab] = []
    // 点击已清分
    if (currentTab == 1) {
      this.setData({
        clickQingFen: 1
      })
    }
  },
  /**
   *  查询对账总体情况
   */
  getSummary: function () {
    var that = this;
    var data = {
      orgSeq: getApp().globalData.orgSeq,
      status: parseInt(this.data.currentTab) + 1
    }
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    common.requestAjax('/api/pay-service/v1/payTrade/queryPayOrderThawRecordInfo', 'POST', data).then(res => {
      wx.hideLoading();
      if (res.data.code == 1) {
        var summary = res.data.result;
        //金额为两位小数
        summary.receivedMoney = summary.receivedMoney.toFixed(2);
        summary.totalMoney = summary.totalMoney.toFixed(2);
        summary.discountMoney = summary.discountMoney.toFixed(2);
        that.setData({
          ["summaryArray[" + this.data.currentTab + "]"]: summary
        })
      }
    }).catch(err => {
      common.showToast("系统异常，请稍后重试！");
    })
  },
  /**
   *  查询对账列表
   */
  getList(page, type) {
    var data = {
      size: 10,
      current: page,
      condition: {
        orgSeq: getApp().globalData.orgSeq,
        status: parseInt(this.data.currentTab) + 1
      }
    };
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    common.requestAjax('/api/pay-service/v1/payTrade/queryPayOrderThawRecordList', 'POST', data).then(res => {
      if (res.data.code == 1) {
        wx.hideLoading();
        var reconciliationList = res.data.records;
        //金额为两位小数
        for (var i = 0; i < reconciliationList.length; i++) {
          reconciliationList[i].receivedMoney = reconciliationList[i].receivedMoney.toFixed(2);
          reconciliationList[i].totalMoney = reconciliationList[i].totalMoney.toFixed(2);
          reconciliationList[i].discountMoney = reconciliationList[i].discountMoney.toFixed(2);
        }
        this.setData({
          ["reconciliationListArray[" + this.data.currentTab + "]"]: this.data.reconciliationListArray[this.data.currentTab].concat(reconciliationList)
        })
        // 点击已清分对数据进行清分
        if (this.data.currentTab == 1 && this.data.clickQingFen == 1) {
          let arr = []
          this.data.reconciliationListArray[1].forEach((item, index) => {
            arr.push(item.thawDate)
          })
          console.log(arr)
          this.checkQingFens(arr)
        }
      } else {
        common.showToast(res.data.message);
      }
    }).catch(err => {
      console.log(err);
    })
  },
  /**
   *  查询到账记录详细
   */
  getOrderDetail: function (e) {
    var orderId = e.currentTarget.dataset.orderid;
    var data = {
      orderId: orderId
    };
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    common.requestAjax('/api/pay-service/v1/payTrade/queryPayOrderThawRecordDetail', 'POST', data).then(res => {
      wx.hideLoading();
      var orderDetail = res.data.result;
      //金额为两位小数
      this.setData({
        orderDetail: orderDetail,
        isShowDialog: true
      })
    }).catch(err => {
      console.log(err);
      common.showToast("系统异常，请稍后重试！");
    })
  },
  /**
   * 开启对账管理
   */
  setManage: function () {
    var currentTab = this.data.currentTab;
    var list = this.data.reconciliationListArray[currentTab];
    if (currentTab == 1) {
      if (list.length == 0) {
        common.showToast("没有需要对账的记录");
        return;
      }
      this.setData({
        manageOpe: true
      })
    }
    if (currentTab == 2) {
      var unfeeList = [];
      for (var i = 0; i < list.length; i++) {
        unfeeList = unfeeList.concat(list[i].unfeeList);
      }
      if (unfeeList.length == 0) {
        common.showToast("没有需要开票的记录");
        return;
      }
      this.setData({
        manageOpeOrder: true
      })
    }
  },
  /**
   * 确认对账
   */
  saveManage: function (e) {
    var that = this;
    var currentTab = this.data.currentTab;
    var data = that.getChoosedItem();
    if (data.length == 0) {
      common.showToast("清选择一条记录");
      return;
    }
    var content = '';
    var url = '';
    if (currentTab == 1) {
      content = '已选择' + data.length + '条记录，确认对账吗？';
      url = '/api/pay-service/v1/payTrade/confirmPayRecordsByDay';
    }
    if (currentTab == 2) {
      content = '已选择' + data.length + '条记录，确认开票吗？';
      // url = '/api/pay-service/v1/payTrade/feePayRecordsByKey';
    }
    let orderIdList = this.data.orderIdList;//订单id
    let feeMoney = this.data.feeMoney;//手续费
    let allPrice = this.data.allPrice;//开票金额
    let type = e.currentTarget.dataset.type;//0清分确认到账 1 手续费开票
    // return
    wx.showModal({
      title: '温馨提示',
      content: content,
      confirmText: "确认",
      cancelText: "取消",
      success: function (res) {
        let feeMoneyNum = 0;
        for (var i = 0; i < feeMoney.length; i++) {
          feeMoneyNum = Number(feeMoneyNum) + Number(feeMoney[i]);
        }
        console.log(feeMoneyNum);

        let price = 0;
        for (var i = 0; i < allPrice.length; i++) {
          price = price + allPrice[i]
        }
        // return;
        if (res.confirm) {
          //0清分确认到账 1 手续费开票
          if (type == 0) {
            wx.showLoading({
              title: '加载中',
              mask: true
            })
            var dataWrap = {
              "orgSeq": getApp().globalData.orgSeq,
              "confirmList": data
            }
            common.requestAjax(url, 'POST', dataWrap).then(res => {
              wx.hideLoading();
              if (res.data.code == 1) {
                common.showToast(res.data.message);
                setTimeout(() => {
                  that.onPullDownRefresh();
                }, 1000)
              } else {
                common.showToast('清分中的订单无法确认到账');
              }
            }).catch(err => {
              wx.hideLoading();
              common.showToast("系统异常，请稍后重试！");
            })
          } else {
            if (feeMoneyNum) {
              wx.navigateTo({
                url: '/pages/myCenter/makeOutInvoice/makeOutInvoice?list=' + orderIdList + '&feeMoneyNum=' + feeMoneyNum.toFixed(2) + '&price=' + price,
              })
            } else {
              wx.showToast({
                title: '开票金额为0，暂不自持开票',
                icon: 'none'
              })
            }
          }

        }
      }
    });
  },
  /**
   * 取消对账
   */
  cancleManage: function () {
    var currentTab = this.data.currentTab;
    if (currentTab == 1) {
      this.setData({
        manageOpe: false
      })
    }
    if (currentTab == 2) {
      this.setData({
        manageOpeOrder: false
      })
    }
  },
  /**
   * 选择记录
   */
  checkboxChange: function (e) {
    var currentTab = this.data.currentTab;
    var list = this.data.reconciliationListArray[currentTab];
    if (currentTab == 1) {
      var thawDate = e.currentTarget.dataset.thawdate;
      var valueArray = e.detail.value;
      var checked = false;
      if (valueArray[0] == thawDate) {
        //如果thawDate值和checkbox返回的值相等，表示选中
        checked = true;
      }
      for (var i = 0; i < list.length; i++) {
        if (list[i].thawDate == thawDate) {
          list[i].checked = checked;
          break;
        }
      }
    }
    if (currentTab == 2) {
      var uuid = e.currentTarget.dataset.uuid;
      var valueArray = e.detail.value;
      var checked = false;
      if (valueArray[0] == uuid) {
        //如果uuid值和checkbox返回的值相等，表示选中
        checked = true;
      }
      for (var i = 0; i < list.length; i++) {
        if (list[i].unfeeList.length != 0) {
          for (var j = 0; j < list[i].unfeeList.length; j++) {
            if (list[i].unfeeList[j].uuid == uuid) {
              list[i].unfeeList[j].checked = checked;
              break;
            }
          }
        }
      }
    }
    this.setData({
      ["reconciliationListArray[" + currentTab + "]"]: list
    })
  },
  /**
   * 全选
   */
  checkboxChangeAll: function (e) {
    var valueArray = e.detail.value;
    var checked = false;
    if (valueArray[0] == 'all') {
      //全选
      checked = true;
    }
    var currentTab = this.data.currentTab;
    var list = this.data.reconciliationListArray[currentTab];
    if (currentTab == 1) {
      for (var i = 0; i < list.length; i++) {
        list[i].checked = checked;
      }
    }
    if (currentTab == 2) {
      for (var i = 0; i < list.length; i++) {
        for (var j = 0; j < list[i].unfeeList.length; j++) {
          list[i].unfeeList[j].checked = checked;
        }
      }
    }
    this.setData({
      ["reconciliationListArray[" + currentTab + "]"]: list
    })
  },
  /**
   * 获取已选择数据列表
   */
  getChoosedItem: function () {
    var data = [];
    var currentTab = this.data.currentTab;
    var list = this.data.reconciliationListArray[currentTab];
    if (currentTab == 1) {
      for (var i = 0; i < list.length; i++) {
        var checked = list[i].checked;
        if (checked) {
          data.push(
            list[i].thawDate
          )
        }
      }
    }
    if (currentTab == 2) {
      let orderIdList = []
      let feeMoneyList = []
      let allPrice = []
      for (var i = 0; i < list.length; i++) {
        for (var j = 0; j < list[i].unfeeList.length; j++) {
          var checked = list[i].unfeeList[j].checked;
          if (checked) {
            data.push(
              list[i].unfeeList[j].uuid
            )
            orderIdList.push(
              list[i].unfeeList[j].orderId
            )
            feeMoneyList.push(
              list[i].unfeeList[j].feeMoney
            )
            allPrice.push(
              list[i].unfeeList[j].receivedMoney
            )
          }
        }
      }
      this.setData({
        orderIdList: orderIdList,
        feeMoney: feeMoneyList,
        allPrice: allPrice
      })
    }
    return data;
  },
  /**
   * 隐藏dialog
   */
  hideDialog: function () {
    this.setData({
      isShowDialog: false,
    });
  },
  /**
   * dialog确认按钮
   */
  confirmDialog: function () {
    this.hideDialog();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // PAGINATE.initMulti();
    this.setData({
      manageOpeOrder: false,
      isIphoneX: getApp().globalData.isIphoneX
    })
    this.switchTab(0);
    // this.getList();
    // this.getSummary()
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    PAGINATE.configMulti = {
      //分页对象是否已经初始化
      inited: false,
      //当前标签页序号
      currentTab: 0,
      //是否在异步请求数据，请求中需要阻止新请求 
      loadingArray: Array(10).fill(false),
      //是否有数据
      hasDataArray: Array(10).fill(true),
      //首次加载是否有数据
      firstHasDataArray: Array(10).fill(true),
      //第几页 
      pageNumArray: Array(10).fill(1),
      //每页多少条数据 
      pageSizeArray: Array(10).fill(10),
      //标签页是否加载过
      tabLoadedArray: Array(10).fill(false),
      //这里注册的参数都会同步到页面上去
      syncParams: ['hasDataArray', 'firstHasDataArray', 'pageNumArray', 'tabLoadedArray']
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    //获取数据
    // this.getSummary();
    // this.getList();
    let pageNumber = this.data.pageNumber;
    pageNumber += 1;
    this.getList(pageNumber, 2)
    wx.showLoading({
      title: '正在加载中...',
    })
    this.setData({
      pageNumber
    })
  },
  // 单个查询清分
  checkQingFen(e, currents, arr) {
    let time = new Date(e.currentTarget.dataset.date);
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();
    let getDay = year + '-' + month + '-' + day
    let timeToday = new Date();
    let yearToday = timeToday.getFullYear();
    let monthToday = timeToday.getMonth() + 1;
    let dayToday = timeToday.getDate();
    let today = yearToday + '-' + monthToday + '-' + dayToday
    if (getDay == today) {  //当前数据时间getDay   系统时间today
      common.showToast('银行次日清分')
      return
    }
    let data = {
      queryDay: e.currentTarget.dataset.date,
      orgSeq: getApp().globalData.orgSeq
    }
    console.log(data)
    common.requestAjax('/api/pay-service/v1/pay/payThawQueryByDay', 'POST', data).then(res => {
      if (res.data.code == 0) {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
        // 清分成功移除该条数据
        // let index = e.currentTarget.dataset.index
        // let array = [...this.data.reconciliationListArray[1]]
        // array.splice(index,1) 
        // this.setData({ 
        //   ["reconciliationListArray[" + this.data.currentTab + "]"]:array 
        // }) 
      }
    }).catch(err => {
      console.log(err)
    })
  },
  // 点击已清分进行清分
  checkQingFens(arr) {
    wx.showLoading({
      title: '清分中',
      mask: true
    })
    let data = {
      queryDays: arr,
      orgSeq: getApp().globalData.orgSeq
    }
    common.requestAjax('/api/pay-service/v1/pay/payThawQueryByDays', 'POST', data).then(res => {
      wx.hideLoading();
      if (res.data.code == 0) {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
        this.setData({
          clickQingFen: 0
        })
        this.data.reconciliationListArray[this.data.currentTab] = []  //清除数据
        this.getList(1, 1) //刷新列表 
      }
    }).catch(err => {
      console.log(err)
    })
  }
})